﻿using log4net;
using Mangox.BLL.Mangox;
using Mangox.BLL.Stock;
using Mangox.Common;
using Mangox.Common.Tookit;
using Mangox.Model.Common;
using Mangox.Model.MangoxDB;
using Mangox.Model.Stock;
using MGXAPI.BLL;
using MGXAPI.Models;
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Reflection;
using System.ServiceModel.Channels;
using System.Text;
using System.Web;
using System.Web.Http;
using Wen.Helpers.Common;

namespace MGXAPI.Controllers.API.Mangox
{
    /// <summary>
    /// 芒果币，微信小程序API
    /// </summary>
    public class UserMgxController : ApiController
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        protected static string className = (new StackTrace()).GetFrame(1).GetMethod().ReflectedType.Name + "/";       //获取类名 
        Random rd = new Random();

        /// <summary>
        /// 获取用户信息 暂时 小程序
        /// http://localhost:13772/api/UserMgx/GetUserApplet?openid=onQm55RBTaOA4uqJbgyELhunHlqI
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        [HttpGet]
        public M_User GetUserApplet(string openid)
        {
            log.Info(className + $"GetUser openid-{openid}");
            try
            {
                MgxUserBLL bll = new MgxUserBLL();
                return bll.GetUserApplet(openid);
            }
            catch (Exception ex)
            {
                log.Error(className + $"GetUser Fail-{ex.ToString()}");
            }
            return null;
        }


        /// <summary>
        /// 获取用户信息API
        /// http://localhost:13772/api/UserMgx/GetUser
        /// param:{"Source":"0","Token":"DDgp61o7H0njRWVNNol4rFpsLfWBrr6/RatRLPpt1/6qTsGCMOkvda7AJCUHPD0VOf4PErgoaOVwdIzTj091DzkJ5cN2kSZm1blnzwHlELcEPB1uoKMN2dZAKuOkSfmY"}
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultModel GetUser(RequestM_UserModel p)
        {
            var reqst = Request;

            ResultModel result = new ResultModel();
            result.Code = -1;

            try
            {
                log.Info(className + $"GetUser param-{JsonCommon.ToJson(p)}");

                #region 验证Token

                var token = MgxCommBLL.DecryptToken(p.Token);
                if (token == null || !token.IsToken)
                {
                    result.Msg = "Token无效或过期";
                    return result;
                }
                result.TokenUpdate = MgxCommBLL.CreateToken(token.UserID.ToString(), token.MgxHashID);
                
                #endregion

                MgxUserBLL bll = new MgxUserBLL();
                var ret = bll.GetUser(token);
                if (ret != null)
                {
                    result.Data = new M_UserResult();
                    ObjectReflection.AutoMapping(ret, result.Data);

                    result.Code = 0;
                    result.Msg = "success";
                }
                else
                {
                    result.Msg = "没找到此用户";
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"GetUser Fail-{ex.ToString()}");
            }
            return result;
        }

        /// <summary>
        /// 创建用户API
        /// 多终端开放
        /// http://localhost:13772/api/UserMgx/CreateUser
        /// 参数：
        /// {{"Source":"0","LoginName":"xiaoming","Password":"123456","UserName":"小明","MgxHashID":"","ERCAddress":"","Mobile":"18888888888","Email":"123456@outlook.com","Gender":"男"}
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultModel CreateUser(RequestM_UserModel p)
        {
            //下面创建了
            //p.UserID = new MgxUserBLL().CreateUserID();
            

            ResultModel result = new ResultModel();
            result.Code = -1;

            log.Info(className + $"CreateUser param-{JsonCommon.ToJson<RequestM_UserModel>(p)}");
            try
            {
                MgxUserBLL bll = new MgxUserBLL();

                /********** 参数验证 *********/
                if (p == null)
                {
                    result.Msg = "参数为空";
                    return result;
                }

                if (string.IsNullOrWhiteSpace(p.LoginName))
                {
                    result.Msg = "用户名不能为空";
                    return result;
                }
                if (p.LoginName.Length < 6)
                {
                    result.Msg = "用户名不能小于6个字符";
                    return result;
                }
                if (p.LoginName.Length > 32)
                {
                    result.Msg = "用户名不能大于32个字符";
                    return result;
                }
                if (bll.GetUserByLoginName(p.LoginName) != null)
                {
                    result.Msg = "此用户名已被注册";
                    return result;
                }
                
                var cpwd = MgxCommBLL.CheckPassword(p.Password);
                if (!string.IsNullOrEmpty(cpwd))
                {
                    result.Msg = cpwd;
                    return result;
                }

                //UserName为空则默认LoginName
                if (string.IsNullOrEmpty(p.UserName))
                {
                    p.UserName = p.LoginName;
                }
                
                if (string.IsNullOrWhiteSpace(p.MgxHashID))
                {
                    //result.Msg = "hash不能为空";
                    //return result;

                    //创建MGX账号Hash
                    p.MgxHashID = MgxBLL.CreateUserHash();
                    if (string.IsNullOrEmpty(p.MgxHashID) || p.MgxHashID.Length != 64)
                    {
                        result.Msg = "创建hash失败";
                        return result;
                    }
                }
                else if (p.MgxHashID.Length != 64)
                {
                    result.Msg = "hash格式不正确";
                    return result;
                }
                
                //创建账号
                p.UserID = new MgxUserBLL().CreateUserID();
                if (p.UserID <= 0)
                {
                    result.Msg = "创建账户失败";
                    return result;
                }

                //密码 加密
                p.Password = MgxCommBLL.GetUserPwd(p.Password);

                //默认值
                p.State = (int)UserStatus.Enabled;
                p.CreateTime = DateTime.Now;
                p.LoginTime = DateTime.Now;
                p.LastLoginTime = DateTime.Now;
                p.LoginCount = 1;
                if (p.Source == null)
                {
                    p.Source = (int)Source_MGX.weizhi;
                }

                p.AppType = (int)AppType.Mango;

                var flag = bll.AddUser(p);
                if (flag)
                {
                    result.Code = 0;
                    result.Msg = "创建用户成功";
                }
                else
                {
                    result.Msg = "创建用户失败";
                }
            }
            catch (Exception ex)
            {
                result.Msg = ex.ToString();
                log.Error(className + $"CreateUser Fail-{ex.ToString()}");
            }
            return result;
        }


        /// <summary>
        /// 更新用户信息
        /// 多终端开放
        /// Token + 用户名 验证是否是有效用户
        /// param:{"Source":"0","Token":"DDgp61o7H0njRWVNNol4rFpsLfWBrr6/RatRLPpt1/6qTsGCMOkvda7AJCUHPD0VOf4PErgoaOVwdIzTj091DzkJ5cN2kSZm1blnzwHlELcEPB1uoKMN2dZAKuOkSfmY","UserName":"xiaoming","ERCAddress":"0xbfd0995ce40e6238CA2dd4f5Bb87709CbDF30e68","Mobile":"18888888888","Email":"xiaoming@outlook.com","Gender":"男"}
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultModel UpdateUser(RequestM_UserModel p)
        {
            ResultModel result = new ResultModel();
            result.Code = -1;

            log.Info(className + $"UpdateUser param-{JsonCommon.ToJson(p)}");
            try
            {                
                //*各种参数验证

                //if (string.IsNullOrWhiteSpace(p.LoginName))
                //{
                //    result.Msg = "无用户名";
                //    return result;
                //}
                
                #region 验证Token

                var token = MgxCommBLL.DecryptToken(p.Token);
                if (token == null || !token.IsToken)
                {
                    result.Msg = "Token无效或过期";
                    return result;
                }
                result.TokenUpdate = MgxCommBLL.CreateToken(token.UserID.ToString(), token.MgxHashID);

                #endregion

                MgxUserBLL bll = new MgxUserBLL();

                var userList = bll.GetUserByUserID(token.UserID.ToString(), AppType.Mango);
                if (userList != null && userList.Count == 1)
                {
                    var user = new M_User();
                    ObjectReflection.AutoMapping(p, user);
                    user.UserID = token.UserID;

                    //校验
                    //if (user.UserName)
                    //{

                    //}

                    //Mobile
                    //Email
                    //Gender

                    var cerc = MgxCommBLL.CheckERCAddress(user.ERCAddress);
                    if (!string.IsNullOrEmpty(cerc))
                    {
                        result.Msg = cerc;
                        return result;
                    }

                    var flag = bll.UpdateUser(user,2);
                    if (flag)
                    {
                        result.Code = 0;
                        result.Msg = "修改成功";
                    }
                    else
                    {
                        result.Msg = "修改失败";
                    }
                }
                else
                {
                    result.Msg = "非有效用户";
                    return result;
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"UpdateUser Fail-{ex.ToString()}");
            }
            return result;
        }

        /// <summary>
        /// 微信点击授权，保存用户详细信息
        /// 参数对象用Post
        /// </summary>
        /// <param name="resCode"></param>
        /// <returns></returns>
        [HttpPost]
        public M_User Auth_wx(WxAuthParam param)
        {
            log.Info(className + $"Auth_wx param-{JsonCommon.ToJson<WxAuthParam>(param)}");
            try
            {
                MgxUserBLL bll = new MgxUserBLL();
                return bll.UpdateAuthUser(param);

            }
            catch (Exception ex)
            {
                log.Error(className + $"Auth_wx Fail-{ex.ToString()}");
            }
            return null;
        }


        #region Test

        /// <summary>
        /// http://localhost:13772/api/UserMgx/test
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string test()
        {
            return "test";
        }

        /// <summary>
        /// http://localhost:13772/api/UserMgx/test2
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public object test2()
        {
            /*读取客户端信息*/
            var grh = Request.GetUrlHelper().ToString();
            String url = Request.RequestUri.ToString();//当前页面地址  
            String userAagent = Request.Headers.UserAgent.ToString();//User-Agent全部信息:里面包含浏览器版本跟操作系统版本  
            String ClientIp = GetClientIp(Request);//客户端IP地址 

            log.Info($"grh-【{grh}】 url-【{url}】 userAagent-【{userAagent}】 ClientIp-【{ClientIp}】");

            return new { id = "123", name = "zhangsan"};
        }

        /* 
         * 获取客户端IP地址-------------- 
         方法说明： this version will return a string with the client IP. If it returns ::1 that means the client is requesting from the same computer as where the API is running. The query address will be something like http://yoursite/api/ip depending on your routing. 
         * （此方法会返回一个IP字符；如果为“：：1”表示客户端的请求来自跟api接口相同的PC机上面。） 
         * 方法来源：http://www.herlitz.nu/2013/06/27/getting-the-client-ip-via-asp-net-web-api/  （国外网站，可能需要FQ才可以呀，在stackoverflow上看到的） 
         */
        private string GetClientIp(HttpRequestMessage request = null)
        {
            request = request ?? Request;

            if (request.Properties.ContainsKey("MS_HttpContext"))
            {
                return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
            }
            else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
            {
                RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
                return prop.Address;
            }
            else if (HttpContext.Current != null)
            {
                return HttpContext.Current.Request.UserHostAddress;
            }
            else
            {
                return null;
            }
        }

        #endregion
    }
}
